let config = require('../config.js');
import {
  $wuxToast
} from '../wux-components/index';

// 控制是否开启全局接口调用输出
const isAllIn = true;

const env = config.env;

function _log(obj) {
  if (env == 'test' || env == 'dev' || isAllIn) {
    console.log('-------------------------' + obj.url + '-----------------------------');
    console.log('method: ' + obj.method);
    console.log('reqData: ' + JSON.stringify(obj.data, null, '\t'))
    console.log('result: ');
    console.log(obj.msg);
    console.log('--------------------/-' + obj.url + '-------------------------------');
  }
}

var Tool = (function() {
  return {
    regExp: {
      email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,
      tel: /(^1[3|4|5|8|7|9|6][0-9]\d{4,8}$)|(^\d{2,5}-\d{7,8}$)/,
      url: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/,
      qb: /^(0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,6})?$/,
      nick: /^[a-zA-Z_\u4E00-\u9FA5\uF900-\uFA2D](4,20)$/, // 英文下划线中文,4-20位
      number: /(^[\-0-9][0-9]*(.[0-9]+)?)$/, // 仅数字
      // 密码6-16位，至少包含数字、字母（区分大小写）、符号中的2种，且不能有空格
      password: /^((?=.*?\d)(?=.*?[A-Za-z])|(?=.*?\d)(?=.*?[!;_\{\}<>\.@#\$%\^&\*\(\)\[\]\\?\\\/\|\-~`\+\=\,\r\n\:\'\"])|(?=.*?[A-Za-z])(?=.*?[!;_\{\}<>\.@#\$%\^&\*\(\)\[\]\\?\\\/\|\-~`\+\=\,\r\n\:\'\"]))[\dA-Za-z!;_\{\}<>\.@#\$%\^&\*\(\)\[\]\\?\\\/\|\-~`\+\=\,\r\n\:\'\"]+$/
    },
    /**
     * 去除首尾空格
     * @param string str
     */
    trim: function(str) {
      return str.replace(/(^\s*)|(\s*$)/g, "");
    },

    /**
     * 获取本地指定数据值
     * @param string k 数据名
     */
    getLocalStorage: function(k) {
      var _aKey = wx.getStorageSync(k);
      return _aKey;
    },

    /**
     * 设置本地指定数据
     * @param string k 数据名
     * @param object v 数据值 
     */
    setLocalStorage: function(k, v) {
      wx.setStorageSync(k, JSON.stringify(v));
    },

    /**
     * 移除本地指定数据
     * @param string k 数据名
     */
    removeLocalStorage: function(k) {
      wx.removeStorageSync(k)
    },

    /**
     * url参数格式化
     * @param object obj
     */
    param: function(obj) {
      var _obj = {};
      var _paramArray = [];
      for (var key in obj) {
        _paramArray.push(key + "=" + obj[key]);
      }
      _obj = _paramArray.join("&");
      return _obj;
    },

    /**
     *获取当前页面路径
     @param boolean isGetParam  是否返回带有url参数的路径
     */
    getCurrentPageUrl: function(isGetParam) {
      var pages = getCurrentPages();
      var currentPage = pages[pages.length - 1];
      var url = currentPage.route;
      var options = currentPage.options;
      if (isGetParam) {
        let urlWithArgs = `/${url}?`;
        for (let key in options) {
          urlWithArgs += `${key}=${options[key]}&`
        }
        return urlWithArgs.substring(0, urlWithArgs.length - 1);
      }
      return "/" + url;
    },

    /**
     * 通用请求接口
     * @param object option
     * --@param boolean debug  是否开启调试
     * --@param string url
     * --@param string method
     * --@param string loadTitle 加载提示语
     * --@param obj data 请求参数对象
     * --@param function success 请求成功函数
     * --@param function fail 请求失败处理函数
     * --@param function error 错误处理函数
     */
    req: function(option) {
      var that = this;
      option.data = option.data || {};

      /**
       * 是否弹出加载框
       */
      if (option.loadTitle) {
        wx.showLoading({
          title: option.loadTitle,
          mask: true
        });
      }

      wx.request({
        url: option.url,
        method: option.method,
        data: option.data,
        header: {
          "content-type": "application/json"
        },
        success: function(res) {
          var _data = res.data;
          if (option.debug && (env === 'test' || env === 'dev') || isAllIn) {
            _log({
              flag: 'success',
              method: option.method,
              url: option.url,
              msg: _data,
              data: option.data
            });
          }

          if (option.loadTitle) {
            wx.hideLoading();
          }
          if (_data.code == config.ERR_OK) {
            // success
            option.success ? option.success(_data.data) : '';
          } else if (_data.code == config.ERR_FAILURE || _data.code == config.ERR_TOKEN_LOST) {
            // token失效 或者 缺少token、userId
            var _currentUrl = that.getCurrentPageUrl(true);
            wx.showToast({
              title: '登录状态失效',
              icon: 'none',
              success: () => {
                wx.redirectTo({
                  url: '/pages/login/index?_url=' + _currentUrl
                });
              }
            })
          } else {
            if (option.error) {
              option.error(_data.msg)
            } else {
              wx.showToast({
                title: option.failTitle ? option.failTitle : (_data.msg ? _data.msg : '发生未知错误'),
                icon: 'none'
              });

            }
          }
        },
        fail: function(err) {
          if (option.debug && (env === 'test' || env === 'dev') || isAllIn) {
            _log({
              flag: 'success',
              method: option.method,
              url: option.url,
              data: option.data
            });
          }

          if (option.loadTitle) {
            wx.hideLoading();
          }
          option.failTitle = option.failTitle || '请求失败';
          var failLog = option.failLog || '调用失败';
          if (option.failTitle) {
            wx.showToast({
              title: option.failTitle,
              icon: 'none'
            });
          }
          option.fail ? option.fail(err) : '';
        }
      });
    },

    formatTime: function(timestamp, split) {
      let stamp = Number(timestamp);
      stamp = String(stamp).length == 13 ? stamp : stamp * 1000;
      let date = timestamp ? new Date(stamp) : new Date();
      let tem = {};
      let _m = date.getMonth() + 1;
      let _d = date.getDate();
      let _h = date.getHours();
      let _min = date.getMinutes();

      tem.year = date.getFullYear();
      tem.month = (_m).toString().length == 1 ? '0' + _m : _m;
      tem.day = (_d).toString().length == 1 ? '0' + _d : _d;
      tem.hour = (_h).toString().length == 1 ? '0' + _h : _h;
      tem.min = (_min).toString().length == 1 ? '0' + _min : _min;
      if (split) {
        return tem.year + split + tem.month + split + tem.day;
      }
      return tem
    },

    /**
     * 显示toast
     * @param string id 是标签元素
     * @param string type 显示类型
     * @param function success 关闭后回调
     */
    toast: function(obj) {
      $wuxToast(obj.id).show({
        type: obj.type ? obj.type : 'default',
        text: obj.text ? obj.text : '未知',
        success: function() {
          try {
            obj.success ? obj.success() : '';
          } catch (e) {
            console.log(e);
          }
        }
      })
    },

    /**
     * 获取用户授权设置
     */
    getUserSetting: function() {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: auth => resolve(auth.authSetting),
          fail: function(err) {
            console.log(fail)
          }
        })
      });
    },

    /**
     * 去除对象内的空键值对
     */
    delSpaceKv: function(obj) {
      for (const key in obj) {
        if (obj[key] === '') {
          delete obj[key]
        }
      }
      return obj
    },
    /**
     * 上传文件或者图片
     * @param string path 文件路径
     * @param string name 服务器接收文件字段的名字
     * @param object formData 额外数据
     * @param function success
     * @param function fail
     */
    onUploadFile: function(url, path, name, formData, success, fail) {
      let base = {
        url: url,
        filePath: path,
        name: name,
        success: (res) => {
          success ? success(JSON.parse(res.data)) : '';
        },
        fail: (res) => {
          fail ? fail(res) : '';
        }
      }
      let param = {};
      if (Object.keys(formData).length > 0) {
        param = Object.assign(base, {
          formData: formData
        });
      } else {
        param = base;
      }
      console.log(param)
      wx.uploadFile(param);
    },

    /**
     * 获取元素高度
     */
    getEleheight: function(id, callback) {
      wx.createSelectorQuery().select(id).boundingClientRect((res) => {
        callback(res);
      }).exec()
    },

  }
})();
module.exports = Tool;